package com.whq.knowverywell.activity;

import java.util.ArrayList;
import java.util.List;

import android.R.color;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import com.whq.knowverywell.R;
import com.whq.knowverywell.adapter.ContentListAdapter;
import com.whq.knowverywell.business.http.model.RegionSalesReturn;
import com.whq.knowverywell.business.http.model.StoreSalseReturn;
import com.whq.knowverywell.business.model.RegionSalesRecord;
import com.whq.knowverywell.business.model.StoreSalesRecord;
import com.whq.knowverywell.task.DomainTask;
import com.whq.knowverywell.task.SummaryTask;
import com.whq.knowverywell.util.LogUtil;
import com.whq.knowverywell.util.TipUtil;
import com.whq.knowverywell.util.constant.ModelConstant;
import com.whq.knowverywell.util.constant.ParamUtil;
import com.whq.knowverywell.view.XListView;
import com.whq.knowverywell.view.XListView.IXListViewListener;

/**
 * content
 * 
 * @author daiwei
 *
 */
public final class ContentFragment extends SherlockFragment implements  SummaryTask.ResultDataListener,DomainTask.ResultDataListener, IXListViewListener, OnItemClickListener {
	private static final String TAG = ContentFragment.class.getSimpleName();
    private static final String KEY_CONTENT = "ContentFragment:Content";

    public static ContentFragment newInstance(int durationType, int businessType, int fragmentType) {
        ContentFragment fragment = new ContentFragment();
        fragment.durationType = durationType;
        fragment.businessType = businessType;
        fragment.fragmentType = fragmentType;
        LogUtil.i(TAG, "parameters durationType[" + durationType + "] businessType[" + businessType + "] fragmentType[" + fragmentType + "]");

        return fragment;
    }

    private String mContent = "数据加载中 ...";
    private List<StoreSalesRecord> mSummaryList = new ArrayList<StoreSalesRecord>();
    private SummaryTask mSummaryTask;
    private List<RegionSalesRecord> mDomainList = new ArrayList<RegionSalesRecord>();
    private DomainTask mDomainTask;
    private List<StoreSalesRecord> mSortList = new ArrayList<StoreSalesRecord>();
    private SummaryTask mSortTask;
    private List<StoreSalesRecord> mGoodsList = new ArrayList<StoreSalesRecord>();
    private SummaryTask mGoodsTask;
    private List<StoreSalesRecord> mHotsellList = new ArrayList<StoreSalesRecord>();
    private SummaryTask mHotsellTask;
    private XListView mXlistView;
    private TextView mPromptTextView;
    private ContentListAdapter mListAdapter;
    private OnSumDataListener mListener;
    
    // yesterday, today, current month, current year
    private int durationType;
    // statics , detail
    private int fragmentType;
    // summary, domain, sort, hotsell
    private int businessType;
    private String orderBy = "";
    private String endCode = "";
    
    @Override
    public void onAttach(Activity activity) {
    	LogUtil.d(TAG, "onAttach start ...");
    	super.onAttach(activity);
    	
    	try {
			mListener = (OnSumDataListener) activity;
		} catch (ClassCastException e) {
			LogUtil.e(TAG, "activity dont implements OnSumDataListener interface .", e);
		}
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
    	LogUtil.d(TAG, "onCreate start ...");
        super.onCreate(savedInstanceState);

        if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
            mContent = savedInstanceState.getString(KEY_CONTENT);
        }
        
        setHasOptionsMenu(true);
        
        getSherlockActivity().getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.top_menu_bg));
        getSherlockActivity().getSupportActionBar().setDisplayShowHomeEnabled(false);
        
		
        if (ModelConstant.FRAGEMENT_TYPE_CONTENT == fragmentType) {
        	getSherlockActivity().getSupportActionBar().setDisplayShowTitleEnabled(false);
        	Context context = getSherlockActivity().getSupportActionBar().getThemedContext();
    		ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(context, R.array.homeitems, R.layout.self_sherlock_spinner_item);
    		list.setDropDownViewResource(R.layout.self_sherlock_spinner_dropdown_item);
    		
    		getSherlockActivity().getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
    		getSherlockActivity().getSupportActionBar().setListNavigationCallbacks(list, (OnNavigationListener) mListener);
    		getSherlockActivity().getSupportActionBar().setSelectedNavigationItem(3);
        } else {
        	getSherlockActivity().getSupportActionBar().setDisplayShowTitleEnabled(true);
        	getSherlockActivity().getSupportActionBar().setTitle("david");
        }
		
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    	LogUtil.d(TAG, "onCreateView start ...");
    	Bundle paramBundle = getArguments();
    	if (paramBundle != null) {
    		durationType = paramBundle.getInt(ParamUtil.BUNDLE_KEY_DURATION_TYPE);
    	}
    	
    	mPromptTextView = new TextView(getActivity());
    	mPromptTextView.setGravity(Gravity.CENTER);
    	mPromptTextView.setText(mContent);
    	mPromptTextView.setTextColor(Color.WHITE);
    	mPromptTextView.setTextSize(10 * getResources().getDisplayMetrics().density);
    	mPromptTextView.setPadding(20, 20, 20, 20);
    	mPromptTextView.setVisibility(View.VISIBLE);
        
        mXlistView = new XListView(getActivity());
        mXlistView.setPullLoadEnable(true);
        mXlistView.setPullRefreshEnable(false);
        mXlistView.setXListViewListener(this);
        mXlistView.setBackgroundColor(color.white);
        mXlistView.setDivider(getResources().getDrawable(R.drawable.content_list_dash));
        switch (businessType) {
		case ModelConstant.BUSINESS_TYPE_SUMMARY:
			mListAdapter = new ContentListAdapter(getActivity(), mSummaryList, businessType);
			break;
			
		case ModelConstant.BUSINESS_TYPE_DOMAIN:
			mListAdapter = new ContentListAdapter(getActivity(), mDomainList, businessType);
			break;

		default:
			break;
		}
        mXlistView.setAdapter(mListAdapter);
        mXlistView.setVisibility(View.GONE);
        
        LinearLayout layout = new LinearLayout(getActivity());
        layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        layout.setGravity(Gravity.CENTER_HORIZONTAL);
        layout.addView(mXlistView);
        layout.addView(mPromptTextView);
        
        return layout;
    }
    
    @Override
    public void onResume() {
    	LogUtil.d(TAG, "onResume start ...");
    	super.onResume();
    	
    	int selectedNavigationIndex = getSherlockActivity().getActionBar().getSelectedNavigationIndex();
    	LogUtil.i(TAG, "selectedNavigationIndex [" + selectedNavigationIndex + "]");
    	
    	switch (selectedNavigationIndex + 1) {
		case ModelConstant.BUSINESS_TYPE_SUMMARY:
			mSummaryTask = new SummaryTask(getActivity(), this, durationType);
	        mSummaryTask.execute(new String[]{orderBy, endCode});
			break;
			
		case ModelConstant.BUSINESS_TYPE_DOMAIN:
			mDomainTask = new DomainTask(getActivity(), this, durationType);
			mDomainTask.execute(new String[]{orderBy, endCode});
			break;

		default:
			break;
		}
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
    	LogUtil.d(TAG, "onSaveInstanceState start ...");
        super.onSaveInstanceState(outState);
        outState.putString(KEY_CONTENT, mContent);
    }

	@Override
	public void handleData(StoreSalseReturn huizongResult) {
		LogUtil.d(TAG, "handleData start ...");
		mXlistView.stopLoadMore();
		mXlistView.stopRefresh();
		
		if (huizongResult == null) {
			mPromptTextView.setText("数据加载异常，请稍后重试。");
			mXlistView.setVisibility(View.GONE);
			mPromptTextView.setVisibility(View.VISIBLE);
			return;
		}
		
		endCode = huizongResult.getEndCode();
		List<StoreSalesRecord> huizongList = huizongResult.getRecordList();
		
		if (huizongList == null || huizongList.size() == 0) {
			LogUtil.w(TAG, "summary is null . ");
			mPromptTextView.setText("没有可以显示的数据。");
			mXlistView.setVisibility(View.GONE);
			mPromptTextView.setVisibility(View.VISIBLE);
			return;
		}
		
		mSummaryList.addAll(huizongList);
		mListAdapter = new ContentListAdapter(getActivity(), mSummaryList, businessType);
        mXlistView.setAdapter(mListAdapter);
        mXlistView.setVisibility(View.VISIBLE);
        mXlistView.setOnItemClickListener(this);
        mPromptTextView.setVisibility(View.GONE);
        mListAdapter.notifyDataSetChanged();
        if (mSummaryTask != null) {
        	mSummaryTask.cancel(true);
        	mSummaryTask = null;
        }
        
        mListener.onSumData(huizongResult.getTotalSalesVolume(), huizongResult.getTotalSalesAmount());
	}
	
	@Override
	public void handleData(RegionSalesReturn domainResult) {
		LogUtil.d(TAG, "handleData start ...");
		mXlistView.stopLoadMore();
		mXlistView.stopRefresh();
		
		if (domainResult == null) {
			mPromptTextView.setText("数据加载异常，请稍后重试。");
			mXlistView.setVisibility(View.GONE);
			mPromptTextView.setVisibility(View.VISIBLE);
			return;
		}
		
		endCode = domainResult.getEndCode();
		List<RegionSalesRecord> domainList = domainResult.getRecordList();
		
		if (domainList == null || domainList.size() == 0) {
			LogUtil.w(TAG, "domain is null . ");
			mPromptTextView.setText("没有可以显示的数据。");
			mXlistView.setVisibility(View.GONE);
			mPromptTextView.setVisibility(View.VISIBLE);
			return;
		}
		
		mDomainList.addAll(domainList);
		mListAdapter = new ContentListAdapter(getActivity(), mSummaryList, businessType);
        mXlistView.setAdapter(mListAdapter);
        mXlistView.setVisibility(View.VISIBLE);
        mXlistView.setOnItemClickListener(this);
        mPromptTextView.setVisibility(View.GONE);
        mListAdapter.notifyDataSetChanged();
        if (mDomainTask != null) {
        	mDomainTask.cancel(true);
        	mDomainTask = null;
        }
        
        //mListener.onSumData(huizongResult.getTotalSalesVolume(), huizongResult.getTotalSalesAmount());
		
	}
	
	public interface OnSumDataListener {
		public void onSumData(long totalSalesVolume, double totalSalesAmount);
	}

	@Override
	public void onRefresh() {
		LogUtil.d(TAG, "onRefresh start ...");
		
	}

	@Override
	public void onLoadMore() {
		LogUtil.d(TAG, "onLoadMore start ...");
		
		switch (businessType) {
		case ModelConstant.BUSINESS_TYPE_SUMMARY:
			mSummaryTask = new SummaryTask(getActivity(), this, durationType);
	        mSummaryTask.execute(new String[]{orderBy, endCode});
			break;
			
		case ModelConstant.BUSINESS_TYPE_DOMAIN:
			mDomainTask = new DomainTask(getActivity(), this, durationType);
			mDomainTask.execute(new String[]{orderBy, endCode});
			break;

		default:
			break;
		}
		
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View convertView, int position, long id) {
		LogUtil.d(TAG, "onItemClick position[" + position + "] id[" + id + "]");
		TipUtil.tipDescription(getActivity(), "onItemClick position[" + position + "] id[" + id + "]");
	}
	
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		LogUtil.d(TAG, "onCreateOptionsMenu start ...");
		
		SubMenu sub1 = menu.addSubMenu("排序");
        sub1.setIcon(R.drawable.top_sort_n);
        sub1.add(0, R.style.Theme_Sherlock, 0, "城市");
        sub1.add(0, R.style.Theme_Sherlock_Light, 1, "销售额");
        sub1.add(0, R.style.Theme_Sherlock_Light_DarkActionBar, 2, "销量");
        sub1.getItem().setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        
        MenuItem item0 = sub1.getItem(0);
        item0.setActionView(R.layout.menu_sort_item);
        item0.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
        TextView sortNameTextView0 = (TextView) item0.getActionView().findViewById(R.id.sort_name_textview);
        sortNameTextView0.setText("城市");
        ImageView sortAscImageView0 = (ImageView) item0.getActionView().findViewById(R.id.sort_asc_imageview);
        sortAscImageView0.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				LogUtil.d(TAG, "城市 asc pressed .");
			}
		});
        ImageView sortDscImageView0 = (ImageView) item0.getActionView().findViewById(R.id.sort_dsc_imageview);
        sortDscImageView0.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				LogUtil.d(TAG, "城市 dsc pressed .");
			}
		});
        
        MenuItem item1 = sub1.getItem(1);
        item1.setActionView(R.layout.menu_sort_item);
        item1.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
        TextView sortNameTextView1 = (TextView) item1.getActionView().findViewById(R.id.sort_name_textview);
        sortNameTextView1.setText("销售额");
        ImageView sortAscImageView1 = (ImageView) item1.getActionView().findViewById(R.id.sort_asc_imageview);
        sortAscImageView1.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				LogUtil.d(TAG, "销售额 asc pressed .");
			}
		});
        ImageView sortDscImageView1 = (ImageView) item1.getActionView().findViewById(R.id.sort_dsc_imageview);
        sortDscImageView1.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				LogUtil.d(TAG, "销售额 dsc pressed .");
			}
		});
        
        MenuItem item2 = sub1.getItem(2);
        item2.setActionView(R.layout.menu_sort_item);
        item2.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
        TextView sortNameTextView2 = (TextView) item2.getActionView().findViewById(R.id.sort_name_textview);
        sortNameTextView2.setText("销量");
        ImageView sortAscImageView2 = (ImageView) item2.getActionView().findViewById(R.id.sort_asc_imageview);
        sortAscImageView2.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				LogUtil.d(TAG, "销量 asc pressed .");
			}
		});
        ImageView sortDscImageView2 = (ImageView) item2.getActionView().findViewById(R.id.sort_dsc_imageview);
        sortDscImageView2.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				LogUtil.d(TAG, "销量 dsc pressed .");
			}
		});
        
        SubMenu sub2 = menu.addSubMenu("刷新");
        sub2.setIcon(R.drawable.top_refresh_n);
        sub2.getItem().setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        
        SubMenu sub = menu.addSubMenu("设置");
        sub.setIcon(R.drawable.btn_set);
        sub.add(0, R.style.Theme_Sherlock, 0, "注销");
        sub.add(0, R.style.Theme_Sherlock_Light, 0, "管理帐号");
        sub.add(0, R.style.Theme_Sherlock_Light_DarkActionBar, 0, "关于");
        sub.getItem().setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		LogUtil.d(TAG, "onOptionsItemSelected start ...");
		
		if (item.getItemId() == android.R.id.home || item.getItemId() == 0) {
            return false;
        }
        Toast.makeText(getActivity(), "Theme changed to \"" + item.getTitle() + "\"", Toast.LENGTH_SHORT).show();
        return true;
	}

	
	
	// ------- customize method -------------
}
